// 通过路线 Id 去查询当前收藏的人数
async function getLikeByLineId(lineId){
  let selectSql = `SELECT COUNT(*) AS total FROM likes WHERE lineId=${lineId} `;
  const selectRow = await global.sql(selectSql)
  if (selectRow.status) {
    return selectRow.data[0].total
  }else {
    return 0
  }
}

// 通过用户 Id 去查询收藏的数量
async function getLikeTotalByUserId(data){
  const { userId } = data
  let selectSql = `SELECT COUNT(*) AS total FROM likes WHERE userId="${userId}" `;
  const selectRow = await global.sql(selectSql)
  if (selectRow.status) {
    return {
      code: 200,
      msg: '请求成功',
      data: selectRow.data[0].total
    }
  }else {
    return {
      code: 500,
      msg: '服务繁忙',
      data: null
    }
  }
}

// 通过 userId 去分页查询当前用户的收藏
async function getLikeByUserId(data) {
  const { userId } = data
  const offset = (data.pageNumber - 1) * 10;
  let selectSql = `SELECT * FROM likes WHERE userId = ${data.userId} ORDER BY createTime ASC LIMIT ? OFFSET ?`;
  const qlParams = [ 10, offset];
  let selectRows = await global.sql(selectSql, qlParams)
  if (selectRows.status) {
    return {
      code: 200,
      msg: '请求成功',
      data: selectRows.data
    }
  }else {
    return {
      code: 500,
      msg: '服务繁忙',
      data:  null
    }
  }
}

// 添加收藏
async function addLike(data) {
  const dateTime = global.commonFun.getNowTime()
  let addSql = `INSERT INTO likes(userId,lineId,createTime) VALUES(?,?,?)`
  const addParams = [ data.userId, data.lineId, dateTime];
  let selectRows = await global.sql(addSql, addParams)
  if (selectRows.status) {
    return {
      code: 200,
      msg: '请求成功',
      data: null
    }
  }else {
    return {
      code: 500,
      msg: '服务繁忙',
      data:  null
    }
  }
}

// 移除收藏
async function removeLike(data) {
  const delSql = `DELETE FROM likes WHERE userId="${data.id}"`
  let selectRows = await global.sql(delSql)
  if (selectRows.status) {
    return {
      code: 200,
      msg: '取消成功',
      data: null
    }
  }else {
    return {
      code: 500,
      msg: '服务繁忙',
      data:  null
    }
  }
}

exports.getLikeTotalByUserId = getLikeTotalByUserId
exports.getLikeByLineId = getLikeByLineId
exports.getLikeByUserId = getLikeByUserId
exports.removeLike = removeLike
exports.addLike = addLike
